package com.fjec.common.interceptor;

import com.fjec.common.enums.EnumSysCode;
import com.fjec.common.exception.SqlInjectException;
import com.vdurmont.emoji.EmojiParser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class SqlInjectInterceptor implements HandlerInterceptor {

    private List<String> whiteList = new ArrayList<>();

    private Pattern pattern = Pattern.compile(".*([';]+|(--)+).*");

    public SqlInjectInterceptor() {
        super();
        whiteList.add("fund_bill_list");
        whiteList.add("sign_type");
        whiteList.add("sign");
        whiteList.add("openid");
        whiteList.add("openId");
        whiteList.add("commitProductInfo");
        whiteList.add("articleContent");
//        whiteList.add("rotationPicUrl");
//        whiteList.add("rotationLinkUrl");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) {

        request.getParameterMap().
                forEach((name, values) -> {
                    matchSqlInject(name, values);
                });

        return true;
    }

    private boolean matchSqlInject(String name, String[] values) {
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                String value = values[i];
                Matcher matcher = pattern.matcher(value);
                boolean isSqlInject = matcher.matches();
                if (isSqlInject) {
                    log.warn("MatchSqlInject name={} , value={} , isSqlInject={}", name, value, isSqlInject);
                    if (!whiteList.contains(name)) {
                        throw new SqlInjectException(EnumSysCode.ERR_0007);
                    }
                }
            }
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse
            response, Object handler, Exception ex) {
    }

    public static void main(String[] args) {
        String value = "<span style=\"background-color: rgb(255, 255, 255); color: rgb(51, 51, 51);\">";
        Pattern pattern = Pattern.compile(".*([';]+|(--)+).*");
        Matcher matcher = pattern.matcher(value);
        boolean isSqlInject = matcher.matches();
        System.out.println(isSqlInject);
    }
}
